#include "mouse_trans.hpp"

#define APP_NAME "[mouse trans]"

MouseTrans::MouseTrans(float unit_move_, float unit_rota_, float unit_scale_)
    :inited(false)
    , pressed(false)
    , rota_x(0)
    , rota_y(0)
    , rota_z(0)
    , move_x(0)
    , move_y(0)
    , scale(1)
    , unit_scale(unit_scale_)
    , unit_move(unit_move_)
    , unit_rota(unit_rota_)
    , logger(spdlog::default_logger())
{
    
}

void MouseTrans::init_matrix(QMatrix4x4 matrix_)
{
    inited = true;
    matrix = matrix_;
}

void MouseTrans::wheel(QWheelEvent *event)
{
    float roll_dist = event->delta();
    float tp_scale =  scale + roll_dist * unit_scale;
    if(tp_scale > 0){
        scale = tp_scale;
    }
    update();
}

void MouseTrans::press(QMouseEvent *event)
{   
	pos_last = event->pos();
    logger->info("{} press {} {} ",APP_NAME,pos_last.x(),pos_last.y());
}

void MouseTrans::move(QMouseEvent *event)
{
	float dx = event->x() - pos_last.x();
    float dy = event->y() - pos_last.y();
    logger->info("{} move {} {} ",APP_NAME,dx,dy);
    if (event->buttons() & Qt::LeftButton)
    {
       move_x = dx * unit_move;
       move_y = dy * unit_move;
    }
    if (event->buttons() & Qt::RightButton)
    {
        set_rota_x(unit_rota * dy);
        set_rota_y(unit_rota * dx);
    }
    update();
    pos_last = event->pos();
}

void MouseTrans::set_rota_x(float angle)
{
    //normalize_angle(angle);
    if (angle != rota_x) {
        rota_x = angle;
    }
}

void MouseTrans::set_rota_y(float angle)
{
    //normalize_angle(angle);
    if (angle != rota_y) {
        rota_y = angle;
    }
}

void MouseTrans::set_rota_z(float angle)
{
    //normalize_angle(angle);
    if (angle != rota_z) {
        rota_z = angle;
    }
}

void MouseTrans::normalize_angle(float &angle)
{
    while (angle < 0)
        angle += 360 * 16;
    while (angle > 360 * 16)
        angle -= 360 * 16;
}

void MouseTrans::update()
{
    matrix.translate(move_x, move_y, 0);
    matrix.rotate(rota_x, 1, 0, 0);
    matrix.rotate(rota_y, 0, 1, 0);
    matrix.rotate(rota_z, 0, 0, 1);
    matrix.scale(scale, scale, scale);
    logger->info("{} {} {} {} {} {} {}",APP_NAME,move_x,move_y,rota_x,rota_y,rota_z,scale);
    emit sig_update();
}

QMatrix4x4 MouseTrans::get_matrix()
{
    return matrix;
}